package com.youmingxing.dialog;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.activity.login.CompleteInfoActivity;
import com.youmingxing.activity.login.LoginByMobleActivity;
import com.youmingxing.activity.login.RegisterByMobileActivity;
import com.youmingxing.activity.WebViewActivity;
import com.youmingxing.bean.Web;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.network.AccountApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.utils.ActivityJump;
import com.youmingxing.utils.Const;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.view.DialogManager;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.Map;

/**
 * JHS
 */

public class LoginDialog extends BaseActivity implements  View.OnClickListener {

    //第三方登陆信息
    private String uid;
    private String userName;
    private String userImage;
    UMSocialService mController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_login);
        mController = UMServiceFactory.getUMSocialService("com.umeng.login");
        //设置新浪SSO handler
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, Const.APPID_QQ,
                Const.APP_KEY_QQ);
        qqSsoHandler.addToSocialSDK();
        UMWXHandler wxHandler = new UMWXHandler(this, Const.APPID_WEIXIN,
                Const.SECRET_WEIXIN);
        wxHandler.setRefreshTokenAvailable(false);
        wxHandler.addToSocialSDK();
        Log.LOG = true;
        initViewTest();
    }


    private void initViewTest() {
        TextView registerByMobile = (TextView) findViewById(R.id.regist_moble_btn);
        LinearLayout agreementTv = (LinearLayout) findViewById(R.id.login_agreement_ll);

        LinearLayout qqLogin = (LinearLayout) findViewById(R.id.qq_ll);
        LinearLayout wechatLogin = (LinearLayout) findViewById(R.id.wechat_ll);
        LinearLayout weiboLogin = (LinearLayout) findViewById(R.id.microblog_ll);
        TextView loginByMobile = (TextView) findViewById(R.id.login_moble_btn);
        ImageView cancel = (ImageView) findViewById(R.id.cancle_img);
        cancel.setOnClickListener(this);
        weiboLogin.setOnClickListener(this);
        wechatLogin.setOnClickListener(this);
        registerByMobile.setOnClickListener(this);
        qqLogin.setOnClickListener(this);
        loginByMobile.setOnClickListener(this);
        agreementTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.regist_moble_btn:
                ActivityJump.getInsanceJump(LoginDialog.this, RegisterByMobileActivity.class, null);
                finish();
                break;
            case R.id.qq_ll:
                mController.doOauthVerify(LoginDialog.this, SHARE_MEDIA.QQ, listener);
                break;
            case R.id.wechat_ll:
                mController.doOauthVerify(LoginDialog.this, SHARE_MEDIA.WEIXIN, listener);
                break;
            case R.id.microblog_ll:
                mController.doOauthVerify(LoginDialog.this, SHARE_MEDIA.SINA, listener);
                break;
            case R.id.login_agreement_ll:
                Intent intent = new Intent(LoginDialog.this, WebViewActivity.class);
                intent.putExtra("web_page", Web.licence);
                startActivity(intent);
                finish();
                break;
            case R.id.login_moble_btn:
                ActivityJump.getInsanceJump(LoginDialog.this, LoginByMobleActivity.class, null);
                finish();
                break;
            case R.id.cancle_img:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }


    SocializeListeners.UMAuthListener listener = new SocializeListeners.UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
            DialogManager.showDialog(LoginDialog.this);

        }

        @Override
        public void onComplete(Bundle bundle, final SHARE_MEDIA share_media) {
            uid = bundle.getString("uid");
            // 判断是否成功
            if (bundle != null && !TextUtils.isEmpty(uid)) {
                Toast.makeText(LoginDialog.this, "授权成功.", Toast.LENGTH_SHORT).show();
                //获取用户信息
                mController.getPlatformInfo(LoginDialog.this, share_media, new SocializeListeners
                        .UMDataListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if (status == 200 && info != null) {
                            if (share_media == SHARE_MEDIA.QQ) {
                                userName = info.get("screen_name").toString();
                                userImage = info.get("profile_image_url").toString();
                                AccountApi.loginByOuth(uid, userName, info.get("profile_image_url").toString(),
                                        "qq", othuLoginHandler);
                            } else if (share_media == SHARE_MEDIA.SINA) {
                                userName = info.get("screen_name").toString();
                                userImage = info.get("profile_image_url").toString();
                                AccountApi.loginByOuth(uid, userName, userImage,
                                        "weibo", othuLoginHandler);
                            } else {
                                //wechat
                                userName = info.get("nickname").toString();
                                userImage = info.get("headimgurl").toString();
                                AccountApi.loginByOuth(uid, info.get("nickname").toString(), info.get("headimgurl").toString(),
                                        "wechat", othuLoginHandler);
                            }

                        } else {
                            android.util.Log.d("TestData", "发生错误：" + status);
                        }
                    }
                });
            } else {
                Toast.makeText(LoginDialog.this, "授权失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SocializeException e, SHARE_MEDIA share_media) {
            android.util.Log.d("error",e.toString());
            DialogManager.dismissDialog();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            android.util.Log.d("error",share_media+"");
            DialogManager.dismissDialog();
        }
    };

    JsonHttpResponseHandler othuLoginHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            DialogManager.dismissDialog();
            if (response.optInt("status") == 200) {
                LogUtil.i("------response--othuLoginHandler--","" + response);

                final JSONObject data = response.optJSONObject("data");
                GlobalDataManager.token = data.optString("token");
                EMClient.getInstance().login(data.optString("hx_id"), data.optString("hx_pwd"), new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        LogUtil.i("------response--onSuccess--","onSuccess"  );

                    }

                    @Override
                    public void onError(int i, String s) {
                        LogUtil.i("------response--onSuccess--","s" +s );
                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
                GlobalDataManager.save();
                //设置推送别名
                MiPushClient.setAlias(getApplicationContext(), GlobalDataManager.token, null);
                SelfInfoApi.getSelfInfo(new BaseJsonHandler
                        (LoginDialog.this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        GlobalDataManager.userId = response.optJSONObject
                                ("data").optInt("id");
                        GlobalDataManager.userInfo = response.toString();
                        GlobalDataManager.save();
                        if (data.optLong("lastLogin") == 0) {
                            //新用户
                            Intent intent = new Intent(LoginDialog.this, CompleteInfoActivity.class);
                            intent.putExtra("third_login", true);
                            intent.putExtra("user_name", userName);
                            intent.putExtra("user_image", userImage);
                            startActivity(intent);
                            finish();
                        } else {
                            //老用户,非第一次登陆
                            finish();
                        }
                    }
                });


            } else {
                Toast.makeText(LoginDialog.this, "登录失败" + response.optString("statusText"), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            DialogManager.dismissDialog();
            Toast.makeText(LoginDialog.this, "登录失败:错误码"+statusCode, Toast.LENGTH_SHORT).show();
        }
    };
}
